package com.xuecheng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.execption.XueChengPlusException;
import com.xuecheng.mapper.*;
import com.xuecheng.model.PageParams;
import com.xuecheng.model.PageResult;
import com.xuecheng.model.dto.AddCourseDto;
import com.xuecheng.model.dto.CourseBaseInfoDto;
import com.xuecheng.model.dto.EditCourseDto;
import com.xuecheng.model.dto.QueryCourseParamsDto;
import com.xuecheng.model.po.CourseBase;
import com.xuecheng.model.po.CourseCategory;
import com.xuecheng.model.po.CourseMarket;
import com.xuecheng.model.po.Teachplan;
import com.xuecheng.service.CourseBaseInfoService;
import com.xuecheng.service.CourseTeacherService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 小班哥
 * @version 1.0
 * @date 2023/3/12 14:41
 * @description  课程信息管理业务接口实现类
 */

@Slf4j
@Service
public class CourseBaseInfoServiceImpl extends ServiceImpl<CourseBaseMapper,CourseBase> implements CourseBaseInfoService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Autowired
    private CourseTeacherService teacherService;

    @Autowired
    private TeachplanMapper teacherMapper;



    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId,PageParams pageParams, QueryCourseParamsDto queryDto) {
        //设置查询条件
        LambdaQueryWrapper<CourseBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //构建查询条件：根据课程名称进行模糊查询
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(queryDto.getCourseName()) , CourseBase::getName , queryDto.getCourseName());
        //构建查询条件：根据课程审核状态查询
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(queryDto.getAuditStatus()) , CourseBase::getAuditStatus , queryDto.getAuditStatus());
        //构建查询条件：根据课程发布状态
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(queryDto.getPublishStatus()) , CourseBase::getStatus , queryDto.getPublishStatus());
        //根据机构ID查询
        lambdaQueryWrapper.eq(CourseBase::getCompanyId , companyId);
        //构建分页对象
        Page<CourseBase> courseBasePage = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        //执行查询
        Page<CourseBase> selectPage = courseBaseMapper.selectPage(courseBasePage, lambdaQueryWrapper);
        //获取查询结果的数据
        List<CourseBase> list = selectPage.getRecords();
        //获取总条数
        long current = selectPage.getTotal();
        PageResult<CourseBase> courseBasePageResult = new PageResult<>(list, current, pageParams.getPageNo(), pageParams.getPageSize());
        return courseBasePageResult;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {
        //校验，不要太相信前端，到啥时候背锅的是后端
         CheckDate(dto);
        //添加基本信息课程信息，因为是新增所以要给他设置一些默认值
        CourseBaseInfoDto baseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(dto , baseInfoDto);
        baseInfoDto.setCompanyId(companyId);
        baseInfoDto.setAuditStatus("202002");
        baseInfoDto.setStatus("203001");
        baseInfoDto.setCreateDate(LocalDateTime.now());

        //插入课程基本信息
//        int BaseCount = courseBaseMapper.(baseInfoDto);
        boolean save = this.save(baseInfoDto);
        System.out.println(baseInfoDto);
        //添加课程营销信息
        int MarketCount = MarketUPorInst(dto , baseInfoDto.getId());

        if (save == false || MarketCount <= 0){
            throw new XueChengPlusException("课程添加失败");
        }
        //添加成功返对应消息
        return getCourseBaseInfo(baseInfoDto.getId());
    }

    /**
     * 修改及添加课程基本信息
     * @param
     * @return
     */
    private int MarketUPorInst(AddCourseDto dto , long courseID) {
        //校验收费规则
        if (StringUtils.isBlank(dto.getCharge())){
            throw new XueChengPlusException("您没有设置收费规则");
        }
        CourseMarket NewCourseMarket = new CourseMarket();
        BeanUtils.copyProperties(dto , NewCourseMarket);
        NewCourseMarket.setId(courseID);
        if (dto.getCharge().equals("201001")){
            //因为AddCourseDto的price的类型是BigDecimal，CourseMarket的price的类型是float类型，拷贝赋值给他时会出现空值
            //这里我呢手动给他赋值
            if (dto.getPrice() == null || dto.getPrice().intValue() <= 0){
                throw new XueChengPlusException("课程设置收费选项，价格不能为空且必须大于0");
            }
            NewCourseMarket.setPrice(dto.getPrice().floatValue());
            NewCourseMarket.setOriginalPrice(dto.getOriginalPrice().floatValue());
        }
        CourseMarket selectById = courseMarketMapper.selectById(NewCourseMarket.getId());
        if (selectById != null){
             return courseMarketMapper.updateById(NewCourseMarket);
        }else {
            return courseMarketMapper.insert(NewCourseMarket);
        }
    }


    /**
     * 修改课程基本信息
     * @Long  companyId
     * @EditCourseDto dto
     * @return
     */
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto dto) {
        CourseBase courseBase = courseBaseMapper.selectById(dto.getId());
        //提交时查询数据库是否存在这条数据
        if (courseBase == null){
            throw new XueChengPlusException("课程不存在");
        }
        //本机构只能修改本机构的课程信息
        if (!companyId.equals(courseBase.getCompanyId())){
            throw new XueChengPlusException("本机构只能修改本机构的课程信息");
        }

        //封装数据
        BeanUtils.copyProperties(dto , courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        //修改课程信息
        int BaseCount = courseBaseMapper.updateById(courseBase);
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(dto , courseMarket);
        courseMarket.setId(dto.getId());
        //修改课程营销信息
        int MarketUpdate = MarketUPorInst(dto , dto.getId());
        if (BaseCount <= 0 || MarketUpdate <= 0 ){
            throw new XueChengPlusException("修改失败");
        }
        //修改成功返回课程基本信息
        return getCourseBaseInfo(courseBase.getId());
    }


    /**
     * 删除课程需要删除课程相关的基本信息、营销信息、课程计划、课程教师信息。
     * @param companyId 机构ID
     * @param course 课程ID
     */
    @Transactional
    @Override
    public void DeleteCourseInfoByID(long companyId , Long course) {
        CourseBase courseBase = courseBaseMapper.selectById(course);
        if (courseBase.getCompanyId() != companyId){
            throw new XueChengPlusException("只能删除本机构的课程");
        }
        //删除课程基本信息
        courseBaseMapper.deleteById(course);
        //删除课程营销信息
        courseMarketMapper.deleteById(course);
        //删除课程教师信息
        teacherService.DeleteTeacherInfo(course , 0);
        //删除课程章节信息
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId , course);
        teacherMapper.delete(queryWrapper);
    }

    /**
     * 根据ID查询课程信息
     * @param id
     * @return
     */
    public CourseBaseInfoDto getCourseBaseInfo(long id) {
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        CourseBase courseBase = courseBaseMapper.selectById(id);
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        if (courseBase != null)
            BeanUtils.copyProperties(courseBase , courseBaseInfoDto);
        if (courseMarket != null)
            BeanUtils.copyProperties(courseMarket , courseBaseInfoDto);
        CourseCategory courseCategoryMT = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryMT.getName());
        CourseCategory courseCategoryST = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryST.getName());
        return courseBaseInfoDto;
    }


    /**
     * 非空校验
     * @param dto
     */
    private void CheckDate(AddCourseDto dto) {
        if(StringUtils.isBlank(dto.getName())){
            throw new XueChengPlusException("课程名称不能为空");
        }
        if (StringUtils.isBlank(dto.getMt())) {
            throw new XueChengPlusException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getSt())) {
            throw new XueChengPlusException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getGrade())) {
            throw new XueChengPlusException("课程等级为空");
        }

        if (StringUtils.isBlank(dto.getTeachmode())) {
            throw new XueChengPlusException("教育模式为空");
        }

        if (StringUtils.isBlank(dto.getUsers())) {
            throw new XueChengPlusException("适应人群为空");
        }

        if (StringUtils.isBlank(dto.getCharge())) {
            throw new XueChengPlusException("收费规则为空");
        }
    }
}
